#!/bin/bash

# @file create-sprout-nginx-config
#
# Copyright (C) Metaswitch Networks 2016
# If license terms are provided to you in a COPYING file in the root directory
# of the source code repository by which you are accessing this code, then
# the license outlined in that COPYING file applies to your use.
# Otherwise no rights are granted except for those provided to you by
# Metaswitch Networks in a separate written agreement.

# This file creates an nginx config file for sprout.

. /etc/clearwater/config

split_domain_and_port()
{
  echo $1 | perl -ne '$_ =~ /(.+):([0-9]+)$/ && print "$1 $2\n"'
}

if [ -n "$sprout_hostname_mgmt" ]
then
  site_file=/etc/nginx/sites-available/sprout
  enabled_file=/etc/nginx/sites-enabled/sprout
  temp_file=$(mktemp sprout.nginx.XXXXXXXX)
  server_name_and_port=( $( split_domain_and_port $sprout_hostname_mgmt ) )

  cat > $temp_file << EOF
upstream http_sprout {
        server unix:/tmp/sprout-http-mgmt-socket;

        # The minimum number of idle connections to keep alive to the upstream.
        keepalive 2;
}

server {
        listen       [::]:9886 ipv6only=off;
        server_name  ${server_name_and_port[0]};

        location / {
                proxy_pass http://http_sprout;
                proxy_http_version 1.1;

                # The client may have instructed the server to close the
                # connection - do not forward this upstream.
                proxy_set_header Connection "";
        }
}
EOF

  if ! diff $temp_file $enabled_file > /dev/null 2>&1
  then
    # Update the site file
    mv $temp_file $site_file

    # Enable the sprout nginx site
    if ( nginx_ensite sprout > /dev/null )
    then
      service nginx stop
    fi
  else
    rm $temp_file
  fi
fi
